import {
  apiGetProductsList
} from "../../service/api/shop";
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperList: [{
        img: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner2.png',
      },
      {
        img: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner3.png',
      },
      {
        img: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner4.png',
      },
      {
        img: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner5.png',
      },
      {
        img: 'https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner6.png',
      },
    ],
    productsList: [],
    productShow: false,
    productDetail: {},
    productNum: 1,
  },

  //跳转搜索页面
  gotoSearch() {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  // 打开商品详情页
  openDetail(e) {
    const productDetail = e.currentTarget.dataset.item;
    this.setData({
      productShow: true,
      productDetail,
    });
  },

  onClose() {
    this.setData({
      productShow: false
    });
  },

  onChange(event) {
    this.setData({
      productNum: event.detail
    })
  },

  // 加入购物车
  addCard() {
    const {
      id,
      name,
      img,
      price
    } = this.data.productDetail;
    const num = this.data.productNum;
    const cardData = wx.getStorageSync('card-data') || [];
    const idx = cardData.findIndex(item => item.id == id);
    if (idx > -1) {
      cardData[idx].num += num;
    } else {
      cardData.push({
        id,
        name,
        img,
        price,
        num
      })
    }
    wx.setStorageSync('card-data', cardData);
    Toast.success('添加成功');
    this.onClose();
    this.setData({
      productNum: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    apiGetProductsList({
      shop_id: 1
    }).then(res => {
      this.setData({
        productsList: res?.data
      })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})